package com.example.servicelogin.exception;
import com.example.login.dto.TokenUserInfoDto;
import com.example.servicelogin.services.impl.RedisServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;



//拦截器
@Component
public class LoginCheckedInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisServiceImpl redisService;
//    调用目标资源执行前   true:放行   false：拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

        // 获取请求路径
        String uri = request.getRequestURI();
        // 排除静态资源及登录接口
        if (uri.startsWith("/static/") || uri.startsWith("/api/login/checkCode")
                || uri.startsWith("/api/login/login")) {
            return true;
        }
        String token = "netty:token:" + request.getParameter("token");
        try {
            TokenUserInfoDto tokenUserInfoDto = redisService.get(token,TokenUserInfoDto.class);
            System.out.println("11111111--11----"+tokenUserInfoDto);
            if(tokenUserInfoDto == null){
                System.out.println("请求被过滤");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }



        String usernameParam = request.getParameter("token");
        if (usernameParam != null) {
            return true;
        }
        // 获取Session中的用户信息
        // 未登录处理
        return false;
    }

//    目标资源执行后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

//    请求资源处理后调用
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}
